import React, { useEffect, useState, useRef, useCallback } from 'react';
import styles from './ChatAi.module.css';

// API配置 - 使用后端代理
const BACKEND_API_BASE_URL = 'http://localhost:3001/api/dify';

// 会话数据结构
const createNewSession = () => ({
  id: Date.now().toString(),
  title: '新对话',
  messages: [],
  createdAt: new Date(),
  updatedAt: new Date()
});

export default function AIPage() {
  const [chatMessages, setChatMessages] = useState([]);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [copiedIndex, setCopiedIndex] = useState(null);
  const chatContentRef = useRef(null);
  
  // 文件上传相关状态
  const [uploadedFiles, setUploadedFiles] = useState([]);
  const fileInputRef = useRef(null);
  const [isDragOver, setIsDragOver] = useState(false);
  
  // 工作流状态跟踪
  const workflowStatus = useRef({ started: false, finished: false, failed: false });
  
  // 中断控制相关
  const abortControllerRef = useRef(null);
  const [isStreaming, setIsStreaming] = useState(false);

  // 中断AI回复
  const stopAIResponse = useCallback(() => {
    console.log('用户请求中断AI回复');
    
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }
    setIsStreaming(false);
    setIsAnalyzing(false);
    
    // 显示中断成功提示
    const notification = document.createElement('div');
    notification.className = styles['interrupt-notification'];
    notification.textContent = '已中断AI回复';
    notification.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      background: #52c41a;
      color: white;
      padding: 8px 16px;
      border-radius: 4px;
      z-index: 1001;
      font-size: 14px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.2);
      animation: slideInRight 0.3s ease;
    `;
    document.body.appendChild(notification);
    setTimeout(() => {
      notification.remove();
    }, 2000);
    
    // 更新最后一条AI消息，移除加载状态
    setChatMessages(prev => {
      const newMessages = [...prev];
      if (newMessages.length > 0 && newMessages[newMessages.length - 1].type === 'ai') {
        const lastMessage = newMessages[newMessages.length - 1];
        if (lastMessage.isLoading) {
          lastMessage.isLoading = false;
          lastMessage.showActions = true;
          // 如果内容为空或只有加载指示器，显示中断消息
          if (!lastMessage.content || typeof lastMessage.content === 'object') {
            lastMessage.content = '回复已中断';
          }
        }
      }
      return newMessages;
    });
  }, []);

  // 侧边栏相关状态
  const [sessions, setSessions] = useState([]);
  const [currentSessionId, setCurrentSessionId] = useState(null);
  const [sidebarVisible, setSidebarVisible] = useState(true);

  // 序列化消息，只保存纯文本内容
  const serializeMessages = useCallback((messages) => {
    return messages.map(msg => ({
      type: msg.type,
      content: (() => {
        if (typeof msg.content === 'string') {
          return msg.content;
        } else if (msg.content && typeof msg.content === 'object' && msg.content.props) {
          // 简单提取文本内容
          const extractText = (element) => {
            if (typeof element === 'string') {
              return element;
            } else if (element && element.props && element.props.children) {
              if (Array.isArray(element.props.children)) {
                return element.props.children.map(extractText).join('');
              } else {
                return extractText(element.props.children);
              }
            }
            return '';
          };
          return extractText(msg.content);
        }
        return '';
      })(),
      showActions: msg.showActions || false,
      isLoading: msg.isLoading || false
    }));
  }, []);

  // 保存会话到localStorage
  const saveSessionsToStorage = useCallback((updatedSessions) => {
    // 序列化每个会话的消息
    const serializedSessions = updatedSessions.map(session => ({
      ...session,
      messages: serializeMessages(session.messages)
    }));
    localStorage.setItem('ai-chat-sessions', JSON.stringify(serializedSessions));
  }, [serializeMessages]);

  // 创建新会话
  const createNewChatSession = useCallback(() => {
    const newSession = createNewSession();
    setSessions(prev => {
      const updatedSessions = [...prev, newSession];
      saveSessionsToStorage(updatedSessions);
      return updatedSessions;
    });
    setCurrentSessionId(newSession.id);
    setChatMessages([]);
    setInputValue('');
    setUploadedFiles([]);
  }, [saveSessionsToStorage]);

  // 初始化：从localStorage加载会话数据
  useEffect(() => {
    // 临时清除localStorage以解决渲染问题
    localStorage.removeItem('ai-chat-sessions');
    
    // 直接创建新会话
    createNewChatSession();
  }, [createNewChatSession]);

  // 切换会话
  const switchSession = useCallback((sessionId) => {
    const session = sessions.find(s => s.id === sessionId);
    if (session) {
      setCurrentSessionId(sessionId);
      // 将纯文本消息转换为React组件格式
      const convertedMessages = session.messages.map(msg => ({
        ...msg,
        content: typeof msg.content === 'string' && msg.content.trim() ? (
          <span style={{ whiteSpace: 'pre-wrap', lineHeight: '1.6' }}>
            {msg.content}
          </span>
        ) : ''
      }));
      setChatMessages(convertedMessages);
      setInputValue('');
      setUploadedFiles([]);
    }
  }, [sessions]);

  // 删除会话
  const deleteSession = useCallback((sessionId) => {
    setSessions(prev => {
      const updatedSessions = prev.filter(s => s.id !== sessionId);
      saveSessionsToStorage(updatedSessions);
      return updatedSessions;
    });
    
    // 如果删除的是当前会话，切换到其他会话或创建新会话
    if (sessionId === currentSessionId) {
      const remainingSessions = sessions.filter(s => s.id !== sessionId);
      if (remainingSessions.length > 0) {
        switchSession(remainingSessions[0].id);
      } else {
        createNewChatSession();
      }
    }
  }, [currentSessionId, sessions, switchSession, createNewChatSession, saveSessionsToStorage]);

  // 更新当前会话的消息
  const updateCurrentSession = useCallback((messages) => {
    setSessions(prev => {
      const updatedSessions = prev.map(session => {
        if (session.id === currentSessionId) {
          const updatedSession = {
            ...session,
            messages: messages,
            updatedAt: new Date()
          };
          
          // 更新会话标题（基于第一条用户消息）
          const firstUserMessage = messages.find(msg => msg.type === 'user');
          if (firstUserMessage) {
            const userText = typeof firstUserMessage.content === 'string' 
              ? firstUserMessage.content 
              : firstUserMessage.content?.props?.children || '';
            updatedSession.title = userText.length > 20 
              ? userText.substring(0, 20) + '...' 
              : userText || '新对话';
          }
          
          return updatedSession;
        }
        return session;
      });
      // 注意：这里不直接调用 saveSessionsToStorage，因为 messages 包含 React 组件
      // 我们将在 useEffect 中处理保存逻辑
      return updatedSessions;
    });
  }, [currentSessionId]);

  // 当聊天消息更新时，同步更新当前会话
  useEffect(() => {
    if (currentSessionId && chatMessages.length > 0) {
      updateCurrentSession(chatMessages);
      
      // 单独处理保存逻辑，确保只保存序列化的消息
      setSessions(prev => {
        const updatedSessions = prev.map(session => {
          if (session.id === currentSessionId) {
            return {
              ...session,
              messages: serializeMessages(chatMessages),
              updatedAt: new Date()
            };
          }
          return session;
        });
        
        // 保存到 localStorage
        const serializedSessions = updatedSessions.map(session => ({
          ...session,
          messages: serializeMessages(session.messages)
        }));
        localStorage.setItem('ai-chat-sessions', JSON.stringify(serializedSessions));
        
        return updatedSessions;
      });
    }
  }, [chatMessages, currentSessionId, updateCurrentSession, serializeMessages]);


  // 每次 chatMessages 变化时自动滚动到底部
  useEffect(() => {
    if (chatContentRef.current) {
      chatContentRef.current.scrollTop = chatContentRef.current.scrollHeight;
    }
  }, [chatMessages]);

  // 键盘事件处理
  const handleKeyPress = useCallback((e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  }, []);

  // 全局键盘快捷键
  useEffect(() => {
    const handleGlobalKeyDown = (e) => {
      // Ctrl/Cmd + / 聚焦到输入框
      if ((e.ctrlKey || e.metaKey) && e.key === '/') {
        e.preventDefault();
        const inputElement = document.querySelector(`.${styles['chat-input']}`);
        if (inputElement) {
          inputElement.focus();
        }
      }
      // Escape 清空输入框或中断AI回复
      if (e.key === 'Escape') {
        if (isStreaming) {
          e.preventDefault();
          stopAIResponse();
        } else {
          setInputValue('');
          setUploadedFiles([]);
        }
      }
      // Ctrl/Cmd + U 打开文件上传
      if ((e.ctrlKey || e.metaKey) && e.key === 'u') {
        e.preventDefault();
        triggerFileUpload();
      }
    };

    document.addEventListener('keydown', handleGlobalKeyDown);
    return () => {
      document.removeEventListener('keydown', handleGlobalKeyDown);
    };
  }, [isStreaming, stopAIResponse]);

  // 拖拽上传处理
  const handleDragOver = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(true);
  }, []);

  const handleDragLeave = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);
  }, []);

  const handleDrop = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);
    
    const files = e.dataTransfer.files;
    if (files && files.length > 0) {
      handleFilesDrop(files);
    }
  }, []);

  // 处理拖拽文件
  const handleFilesDrop = (files) => {
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      
      // 检查文件类型
      const allowedImageTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/gif'];
      const allowedDocumentTypes = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      ];
      const allAllowedTypes = [...allowedImageTypes, ...allowedDocumentTypes];
      
      if (!allAllowedTypes.includes(file.type)) {
        alert('支持的文件格式：\n图片：PNG, JPEG, JPG, WebP, GIF\n文档：PDF, DOC, DOCX');
        continue;
      }

      // 检查文件大小（限制为 10MB）
      if (file.size > 10 * 1024 * 1024) {
        alert('文件大小不能超过 10MB');
        continue;
      }

      // 添加文件
      addImageFile(file).catch(error => {
        console.error('文件处理失败:', error);
      });
    }
  };



  const formatAIResponse = (text) => {
    // 移除所有数学符号和格式标记，保持纯文本显示
    text = text
      // 移除LaTeX数学符号
      .replace(/\\[\(\)\[\]]/g, '')  // 移除 \( \) \[ \]
      .replace(/\\quad/g, ' ')       // 移除 \quad
      .replace(/\\times/g, '×')      // 替换 \times 为 ×
      .replace(/\\div/g, '÷')        // 替换 \div 为 ÷
      .replace(/\\frac\{([^}]+)\}\{([^}]+)\}/g, '$1/$2')  // 简化分数
      .replace(/\\boxed\{([^}]+)\}/g, '$1')  // 移除 \boxed
      // 移除Markdown格式
      .replace(/\*\*(.*?)\*\*/g, '$1')  // 移除 **粗体**
      .replace(/__(.*?)__/g, '$1')      // 移除 __下划线__
      .replace(/`(.*?)`/g, '$1')        // 移除 `代码`
      // 简化列表格式
      .replace(/^\d+\.\s+/gm, '')      // 移除数字列表
      .replace(/^[-*]\s+/gm, '')       // 移除无序列表
      // 处理段落分隔
      .replace(/\n\n+/g, '\n\n');
    
    return text;
  };

  // 文件上传函数
  const uploadFile = async (file) => {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const token = localStorage.getItem('token');
      const response = await fetch(`${BACKEND_API_BASE_URL}/upload-file`, {
        method: 'POST',
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        },
        body: formData
      });

      if (!response.ok) {
        const errorData = await response.text();
        console.error('❌ 文件上传失败:', response.status, errorData);
        throw new Error(`文件上传失败: ${response.status} - ${errorData}`);
      }

      const result = await response.json();

      
      // 返回文件信息，包括提取的内容
      return {
        fileId: result.fileId,
        extractedContent: result.extractedContent,
        fileName: result.fileName,
        mimeType: result.mimeType
      };
    } catch (error) {
      console.error('❌ 文件上传错误:', error);
      throw error;
    }
  };



  const sendMessage = async () => {
    if (!inputValue.trim()) {
      alert('请输入问题');
      return;
    }

    // 保存输入值，因为后面会清空
    const currentInput = inputValue.trim();
    const filesForMessage = [...uploadedFiles];

    // 启动分析
    setIsAnalyzing(true);
    setIsStreaming(true);
    workflowStatus.current = { started: false, finished: false, failed: false };
    
    // 创建新的 AbortController
    abortControllerRef.current = new AbortController();

    // 构建用户消息 - 简化为纯文本
    const userMessage = currentInput;

    setChatMessages(prev => [...prev, { type: 'user', content: userMessage }]);
    setChatMessages(prev => [...prev, { 
      type: 'ai', 
      content: '正在思考...', 
      showActions: false, 
      timer: 0, 
      isLoading: true 
    }]);

    // 清空输入和文件
    setInputValue('');
    setUploadedFiles([]);

    try {
      // 调用 /chat-messages 接口
      
      // 首先上传所有文件
      const filePromises = filesForMessage.map(async (file) => {
        if (file.fileObject) {
          const uploadResult = await uploadFile(file.fileObject);
          // 根据文件MIME类型确定文件类型
          let fileType = "image";
          if (file.mime_type.startsWith("audio/")) {
            fileType = "audio";
          } else if (file.mime_type.startsWith("video/")) {
            fileType = "video";
          } else if (file.mime_type.startsWith("application/") || 
                     file.mime_type.startsWith("text/")) {
            fileType = "document";
          }
          

          
          // 使用后端期望的文件对象格式，包含文件信息以便类型判断
          const fileObject = {
            fileId: uploadResult.fileId,  // 后端期望的格式
            name: file.name,  // 文件名，用于扩展名判断
            type: file.mime_type,  // MIME类型，用于类型判断
            originalName: file.name,  // 原始文件名，用于显示
            extractedContent: uploadResult.extractedContent  // 提取的文档内容
          };
          

          
          return fileObject;
        }
        return null;
      });
      
      // 等待所有文件上传完成
      const fileResults = await Promise.all(filePromises);
      const validFiles = fileResults.filter(Boolean);
      
      // 等待文件处理完成 - 增加等待时间，特别是对于文档文件
      const hasDocuments = validFiles.some(file => file.type && (file.type.startsWith('application/') || file.type.startsWith('text/')));
      const waitTime = hasDocuments ? 25000 : 5000; // 文档文件等待25秒，图片文件等待5秒
      await new Promise(resolve => setTimeout(resolve, waitTime));
      
      // 简化文件验证，直接等待处理完成
      
      // 额外等待时间，确保文档文件完全处理完成
      if (validFiles.some(file => file.type && (file.type.startsWith('application/') || file.type.startsWith('text/')))) {
        await new Promise(resolve => setTimeout(resolve, 8000)); // 增加等待时间
      }
      

      
      // 准备基本请求数据
      const chatInputs = {
        message: currentInput, // 使用用户原始输入，让工作流自己判断
        files: validFiles.length > 0 ? validFiles : undefined,
        conversationId: ""
      };


       
       // 跳过文件状态验证（避免CORS问题），直接发送请求
      
      // 发送请求
        const response = await fetch(`${BACKEND_API_BASE_URL}/chat-messages`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
            'Accept': 'text/event-stream'  // 使用流式响应
        },
        body: JSON.stringify(chatInputs),
        signal: abortControllerRef.current.signal
      });
      
      if (!response.ok) {
        const errorData = await response.text();
        console.error('API Error:', response.status, errorData);
        
        // 检查是否是文件验证失败错误
        if (errorData.includes('File validation failed') || errorData.includes('Invalid upload file id') || errorData.includes('unsupported_file_type') || errorData.includes('invalid_param')) {

          
          // 对于文档文件，尝试更长的等待时间
          const hasDocuments = validFiles.some(file => file.type && (file.type.startsWith('application/') || file.type.startsWith('text/')));
          if (hasDocuments) {
            await new Promise(resolve => setTimeout(resolve, 10000)); // 额外等待10秒
            const retryResponse = await fetch(`${BACKEND_API_BASE_URL}/chat-messages`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Accept': 'text/event-stream'
              },
              body: JSON.stringify(chatInputs),
              signal: abortControllerRef.current.signal
            });
            
            if (retryResponse.ok) {
              // 使用新的响应变量名避免const重新赋值错误
              const finalResponse = retryResponse;
              // 处理成功的响应
              if (finalResponse.body) {
                const reader = finalResponse.body.getReader();
                const decoder = new TextDecoder();
                
                while (true) {
                  const { done, value } = await reader.read();
                  if (done) break;
                  
                  const chunk = decoder.decode(value);
                  const lines = chunk.split('\n');
                  
                  for (const line of lines) {
                    if (line.startsWith('data: ')) {
                      const data = line.slice(6);
                      if (data === '[DONE]') {
                        break;
                      }
                      
                      try {
                        const parsed = JSON.parse(data);
                        if (parsed.event === 'message') {
                          setChatMessages(prev => {
                            const newMessages = [...prev];
                            const lastMessage = newMessages[newMessages.length - 1];
                            if (lastMessage && lastMessage.type === 'ai') {
                              lastMessage.content = formatAIResponse(parsed.answer);
                              lastMessage.isLoading = false;
                              lastMessage.showActions = true;
                            }
                            return newMessages;
                          });
                        }
                      } catch (e) {
                        // 解析响应数据失败
                      }
                    }
                  }
                }
              }
              return; // 成功处理，直接返回
            } else {
              const retryErrorData = await retryResponse.text();
              console.error('Document retry failed:', retryResponse.status, retryErrorData);
              
                             // 提供更友好的错误信息
               if (retryErrorData.includes('File validation failed')) {
                 throw new Error(`文档文件处理失败。可能的原因：\n1. 文件格式不被Dify支持\n2. 文件内容有问题\n3. 文件处理时间不够\n\n请尝试：\n1. 使用PDF或DOC格式\n2. 检查文件内容是否正常\n3. 稍后重试\n4. 将文档截图作为图片上传`);
               } else {
                 throw new Error(`API error: ${retryResponse.status} - ${retryErrorData}`);
               }
            }
          } else {
            throw new Error(`文件验证失败: ${errorData}`);
          }
        } else {
          throw new Error(`API error: ${response.status} - ${errorData}`);
        }
      }

      // 统一使用流式处理（后端总是返回流式响应）

      // 准备处理流式响应
      setChatMessages(prev => {
        const newMessages = [...prev];
        newMessages.pop(); // 移除加载消息
        newMessages.push({ type: 'ai', content: '', showActions: false, isLoading: false });
        return newMessages;
      });

      let fullResponse = '';
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      
      // 数据缓冲，用于处理不完整的JSON
      let buffer = '';
      
        // 超时检测机制
      let lastMessageTime = Date.now();
        const messageTimeout = 60000; // 60秒超时
      let timeoutChecker = setInterval(() => {
        if (Date.now() - lastMessageTime > messageTimeout) {
          clearInterval(timeoutChecker);
          reader.cancel();
            
            // 显示超时错误
            setChatMessages(prev => {
              const newMessages = [...prev];
              if (newMessages.length > 0) {
                newMessages[newMessages.length - 1] = {
                  type: 'ai', 
                  content: '请求超时，请检查网络连接或稍后重试。',
                  showActions: true,
                  isLoading: false
                };
              }
              return newMessages;
            });
        }
      }, 5000);

      try {
        // 读取流式数据
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            clearInterval(timeoutChecker);
            break;
          }

          // 解码数据块并添加到缓冲区
          const chunk = decoder.decode(value, { stream: true });
          buffer += chunk;
          
          // 重置超时计时器
          lastMessageTime = Date.now();
          
          // 处理SSE格式数据
          const lines = buffer.split('\n');
          // 保留最后一行（可能不完整）
          buffer = lines.pop() || '';
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const jsonStr = line.slice(6); // 去掉 'data: ' 前缀
              
              try {
                if (jsonStr.trim() === '[DONE]') {
                  // 流结束
                  continue;
                }
                
                // 检查JSON字符串是否完整
                if (!jsonStr.trim()) {
                  continue; // 跳过空行
                }
                
                const data = JSON.parse(jsonStr);
                
                // 处理不同类型的事件
                if (data.event === 'message') {
                  // 尝试从多个可能的字段中提取消息内容
                  let messageContent = '';
                  
                  if (data.data?.answer) {
                    messageContent = data.data.answer;
                  } else if (data.answer) {
                    messageContent = data.answer;
                  } else if (data.content) {
                    messageContent = data.content;
                  } else if (data.message) {
                    messageContent = data.message;
                  } else if (data.data?.content) {
                    messageContent = data.data.content;
                  } else if (data.data?.message) {
                    messageContent = data.data.message;
                  }
                  

                  
                  if (messageContent) {
                    fullResponse += messageContent;
                    
                    // 更新界面显示
                    const formattedText = formatAIResponse(fullResponse);
                    setChatMessages(prev => {
                      const newMessages = [...prev];
                      newMessages[newMessages.length - 1] = { 
                        type: 'ai', 
                        content: formattedText, 
                        showActions: false, 
                        isLoading: false 
                      };
                      return newMessages;
                    });
                  }
                } 
                // 工作流开始事件
                else if (data.event === 'workflow_started') {
                    workflowStatus.started = true;
                    
                  setChatMessages(prev => {
                    const newMessages = [...prev];
                    newMessages[newMessages.length - 1] = { 
                      type: 'ai', 
                      content: '正在处理您的请求和文件...', 
                      showActions: false, 
                      isLoading: true 
                    };
                    return newMessages;
                  });
                }
                // 工作流完成事件
                  else if (data.event === 'workflow_finished') {
                    workflowStatus.finished = true;
                  }
                  // 工作流失败事件
                  else if (data.event === 'workflow_failed') {
                    console.error('Workflow failed:', data);
                    workflowStatus.failed = true;
                    
                    const errorMessage = data.data?.message || '工作流执行失败';
                    setChatMessages(prev => {
                      const newMessages = [...prev];
                      newMessages[newMessages.length - 1] = { 
                        type: 'ai', 
                        content: `工作流执行失败: ${errorMessage}`, 
                        showActions: true, 
                        isLoading: false 
                      };
                      return newMessages;
                    });
                    
                    throw new Error(`Workflow failed: ${errorMessage}`);
                  }
                  // 消息完成事件
                  else if (data.event === 'message_end') {
                    
                    if (fullResponse && fullResponse.trim()) {
                      const formattedText = formatAIResponse(fullResponse);
                      setChatMessages(prev => {
                        const newMessages = [...prev];
                        newMessages[newMessages.length - 1] = { 
                          type: 'ai', 
                          content: (
                            <span style={{ whiteSpace: 'pre-wrap', lineHeight: '1.6' }}>
                              {formattedText}
                            </span>
                          ), 
                          showActions: true, 
                          isLoading: false 
                        };
                        return newMessages;
                      });
                    } else {
                      
                      // 检查是否在其他字段中有回复内容
                      let alternativeResponse = null;
                      
                      if (data.answer) {
                          alternativeResponse = data.answer;
                      } else if (data.data && data.data.answer) {
                          alternativeResponse = data.data.answer;
                      } else if (data.content) {
                          alternativeResponse = data.content;
                      } else if (data.message) {
                          alternativeResponse = data.message;
                      }
                      
                      if (alternativeResponse) {
                          const formattedText = formatAIResponse(alternativeResponse);
                    setChatMessages(prev => {
                      const newMessages = [...prev];
                      newMessages[newMessages.length - 1] = { 
                        type: 'ai', 
                        content: (
                          <span style={{ whiteSpace: 'pre-wrap', lineHeight: '1.6' }}>
                            {formattedText}
                                      </span>
                                  ), 
                                  showActions: true, 
                                  isLoading: false 
                              };
                              return newMessages;
                          });
                          return; // 找到替代回复，退出处理
                      }
                      
                      // 如果所有方法都失败，显示默认消息
                      setChatMessages(prev => {
                        const newMessages = [...prev];
                        newMessages[newMessages.length - 1] = { 
                          type: 'ai', 
                          content: (
                            <span style={{ whiteSpace: 'pre-wrap', lineHeight: '1.6' }}>
                              处理完成，但未收到回复内容，请重试。
                          </span>
                        ), 
                        showActions: true, 
                        isLoading: false 
                      };
                      return newMessages;
                    });
                  }
                }
                // 错误事件
                else if (data.event === 'error') {
                  console.error('Error event received:', data);
                    const errorMsg = data.data?.message || '未知错误';
                    throw new Error(`API error: ${errorMsg}`);
                }
              } catch (e) {
                console.error('Error parsing SSE data:', e);
                console.error('Problematic JSON string:', jsonStr);
                console.error('JSON string length:', jsonStr.length);
                
                if (e instanceof SyntaxError) {
                  // 对于JSON解析错误，记录但不中断流程
                  console.warn('JSON parsing failed, skipping this chunk');
                  continue;
                }
                throw e;
              }
            }
          }
        }
        
        // 处理缓冲区中剩余的数据
        if (buffer.trim()) {
          console.log('Processing remaining buffer:', buffer);
          const lines = buffer.split('\n');
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const jsonStr = line.slice(6);
              try {
                if (jsonStr.trim() === '[DONE]' || !jsonStr.trim()) {
                  continue;
                }
                const data = JSON.parse(jsonStr);
                // 处理剩余数据...
                console.log('Processed remaining data:', data);
              } catch (e) {
                console.warn('Failed to parse remaining buffer:', e);
              }
            }
          }
        }
      } catch (streamError) {
        clearInterval(timeoutChecker);
        
        // 检查是否是中断错误
        if (streamError.name === 'AbortError') {
          console.log('流处理已被用户中断');
          return; // 中断错误不需要显示错误消息
        }
        
        console.error('Stream processing error:', streamError);
        
        if (workflowStatus.failed) {
          return;
        }
        
        throw streamError;
      }
      
        // 流结束，显示完整响应
      if (fullResponse) {
        const formattedFinalResponse = formatAIResponse(fullResponse);
        setChatMessages(prev => {
          const newMessages = [...prev];
          if (newMessages.length > 0) {
            newMessages[newMessages.length - 1] = {
              type: 'ai', 
              content: formattedFinalResponse,
              showActions: true,
              isLoading: false
            };
          }
          return newMessages;
        });
      } else if (!workflowStatus.failed) {
        setChatMessages(prev => {
          const newMessages = [...prev];
          if (newMessages.length > 0) {
            newMessages[newMessages.length - 1] = {
              type: 'ai', 
              content: '处理完成，但未收到回复内容，请重试。',
              showActions: true,
              isLoading: false
            };
          }
          return newMessages;
        });
      }
    } catch (error) {
      setIsAnalyzing(false);
      setIsStreaming(false);
      
      // 检查是否是中断错误
      if (error.name === 'AbortError') {
        console.log('请求已被用户中断');
        return; // 中断错误不需要显示错误消息
      }
      
      // 改进的错误消息显示
      let errorMessage = '请求失败';
      if (error.message.includes('API error:')) {
        errorMessage = error.message.replace('API error: ', '');
      } else if (error.message.includes('NetworkError') || error.message.includes('fetch')) {
        errorMessage = '网络连接失败，请检查网络设置';
      } else if (error.message.includes('timeout')) {
        errorMessage = '请求超时，请稍后重试';
      } else {
        errorMessage = `请求失败: ${error.message}`;
      }
      
      setChatMessages(prev => {
        const newMessages = [...prev];
        newMessages.pop();
        return [...newMessages, { type: 'ai', content: errorMessage, showActions: true }];
      });
      console.error('Request failed:', error);
    } finally {
      setIsAnalyzing(false);
      setIsStreaming(false);
      abortControllerRef.current = null;
    }
  };



  const handleCopy = (msg, index) => {
    // 安全提取文本内容
    let text = '';
    if (typeof msg.content === 'string') {
      text = msg.content;
    } else if (msg.content && typeof msg.content === 'object' && msg.content.props) {
      // 尝试从React元素中提取文本
      const extractText = (element) => {
        if (typeof element === 'string') {
          return element;
        } else if (element && element.props && element.props.children) {
          if (Array.isArray(element.props.children)) {
            return element.props.children.map(extractText).join('');
          } else {
            return extractText(element.props.children);
          }
        }
        return '';
      };
      text = extractText(msg.content);
    }
    
    if (text && text.trim()) {
      if (navigator && navigator.clipboard) {
        navigator.clipboard.writeText(text);
      } else {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
      }
      setCopiedIndex(index);
      setTimeout(() => setCopiedIndex(null), 3000);
    }
  };

  const handlePlay = (msg) => {
    // 安全提取文本内容
    let text = '';
    if (typeof msg.content === 'string') {
      text = msg.content;
    } else if (msg.content && typeof msg.content === 'object' && msg.content.props) {
      // 尝试从React元素中提取文本
      const extractText = (element) => {
        if (typeof element === 'string') {
          return element;
        } else if (element && element.props && element.props.children) {
          if (Array.isArray(element.props.children)) {
            return element.props.children.map(extractText).join('');
          } else {
            return extractText(element.props.children);
          }
        }
        return '';
      };
      text = extractText(msg.content);
    }
    
    if (text && text.trim()) {
      if (window.speechSynthesis.speaking) {
        window.speechSynthesis.cancel();
      }
      const utter = new window.SpeechSynthesisUtterance(text);
      utter.lang = 'zh-CN';
      window.speechSynthesis.speak(utter);
    }
  };





  // 添加图片文件函数
  const addImageFile = (file) => {
    return new Promise((resolve, reject) => {
      try {

        
        // 判断文件类型
        const isImage = file.type.startsWith('image/');
        const isDocument = file.type.startsWith('application/') || file.type.startsWith('text/');
        
        // 为文档文件创建预览图标
        let preview;
        if (isImage) {
          preview = URL.createObjectURL(file);
        } else {
          // 为文档文件创建默认预览图标
          const fileIcon = getFileIcon(file.type, file.name);
          preview = fileIcon;
        }
        
        // 保存文件信息
        const uploadedFile = {
          id: `local-file-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
          name: file.name,
          fileObject: file, // 存储文件对象本身
          extension: file.name.split('.').pop(),
          mime_type: file.type,
          size: file.size,
          isImage: isImage,
          isDocument: isDocument,
          preview: preview
        };

        setUploadedFiles(prev => [...prev, uploadedFile]);
        resolve(uploadedFile);
      } catch (error) {
        console.error('❌ 文件处理错误:', error);
        alert(`文件 ${file.name} 处理失败: ${error.message}`);
        reject(error);
      }
    });
  };

  // 获取文件图标
  const getFileIcon = (mimeType, fileName) => {
    const ext = fileName.toLowerCase().split('.').pop();
    
    if (mimeType === 'application/pdf') return '📄';
    if (mimeType === 'application/msword' || ext === 'doc') return '📝';
    if (mimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || ext === 'docx') return '📝';
    if (mimeType === 'application/vnd.ms-excel' || ext === 'xls') return '📊';
    if (mimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || ext === 'xlsx') return '📊';
    if (mimeType === 'text/plain' || ext === 'txt') return '📄';
    if (mimeType === 'text/csv' || ext === 'csv') return '📊';
    
    return '📄'; // 默认文档图标
  };

  // 文件选择处理
  const handleFileSelect = (event) => {
    const files = event.target.files;
    if (!files || files.length === 0) return;


    
    // 验证文件
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      
      // 检查文件类型 - 支持图片和文档格式
      const allowedImageTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/gif'];
      const allowedDocumentTypes = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      ];
      const allAllowedTypes = [...allowedImageTypes, ...allowedDocumentTypes];
      
      if (!allAllowedTypes.includes(file.type)) {
        alert('支持的文件格式：\n图片：PNG, JPEG, JPG, WebP, GIF\n文档：PDF, DOC, DOCX');
        continue;
      }

      // 检查文件大小（限制为 10MB）
      if (file.size > 10 * 1024 * 1024) {
        alert('文件大小不能超过 10MB');
        continue;
      }

      // 添加文件
      addImageFile(file).catch(error => {
        console.error('文件处理失败:', error);
      });
    }

    // 清空文件输入
    event.target.value = '';
  };

  // 触发文件选择
  const triggerFileUpload = () => {
    fileInputRef.current?.click();
  };

  // 粘贴事件处理（支持粘贴图片）
  const handlePaste = useCallback((e) => {
    const items = e.clipboardData?.items;
    if (!items) return;

    let hasImage = false;
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      if (item.type.indexOf('image') !== -1) {
        e.preventDefault();
        hasImage = true;
        const file = item.getAsFile();
        if (file) {
          // 添加粘贴成功的视觉反馈
          const inputElement = e.target;
          inputElement.classList.add(styles['paste-success']);
          setTimeout(() => {
            inputElement.classList.remove(styles['paste-success']);
          }, 500);
          
          addImageFile(file).catch(error => {
            console.error('粘贴图片处理失败:', error);
            alert('粘贴图片失败，请重试');
          });
        }
      }
    }
    
    if (hasImage) {
      // 显示粘贴成功提示
      const notification = document.createElement('div');
      notification.className = styles['paste-notification'];
      notification.textContent = '图片已粘贴';
      notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #28a745;
        color: white;
        padding: 8px 16px;
        border-radius: 4px;
        z-index: 1001;
        font-size: 14px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        animation: slideInRight 0.3s ease;
      `;
      document.body.appendChild(notification);
      setTimeout(() => {
        notification.remove();
      }, 2000);
    }
  }, []);

  // 移除上传的文件
  const removeFile = (fileId) => {
    setUploadedFiles(prev => {
      const newFiles = prev.filter(file => file.id !== fileId);
      
      // 释放本地URL
      const fileToRemove = prev.find(file => file.id === fileId);
      if (fileToRemove && fileToRemove.preview.startsWith('blob:')) {
        URL.revokeObjectURL(fileToRemove.preview);
      }
      
      return newFiles;
    });
  };

  // 返回首页

  return (
    <div className={styles['ai-container']}>
      {/* 移动端遮罩层 */}
      {sidebarVisible && (
        <div 
          className={styles['sidebar-overlay']}
          onClick={() => setSidebarVisible(false)}
        />
      )}
      
      {/* 侧边栏 */}
      <div className={`${styles['sidebar']} ${sidebarVisible ? styles['sidebar-visible'] : ''}`}>
        <div className={styles['sidebar-header']}>
          <button 
            className={styles['new-chat-btn']}
            onClick={createNewChatSession}
            disabled={false}
          >
            <span className={styles['new-chat-icon']}>+</span>
            新建会话
          </button>
          <button 
            className={styles['sidebar-toggle']}
            onClick={() => setSidebarVisible(!sidebarVisible)}
            title={sidebarVisible ? '隐藏侧边栏' : '显示侧边栏'}
          >
            <span>☰</span>
          </button>
        </div>
        
        <div className={styles['sessions-list']}>
          {sessions.map((session) => (
            <div 
              key={session.id}
              className={`${styles['session-item']} ${session.id === currentSessionId ? styles['session-active'] : ''}`}
              onClick={() => switchSession(session.id)}
            >
              <div className={styles['session-content']}>
                <div className={styles['session-title']}>
                  {session.title}
                </div>
                <div className={styles['session-time']}>
                  {new Date(session.updatedAt).toLocaleDateString()}
                </div>
              </div>
              <button 
                className={styles['delete-session-btn']}
                onClick={(e) => {
                  e.stopPropagation();
                  if (window.confirm('确定要删除这个会话吗？')) {
                    deleteSession(session.id);
                  }
                }}
                title="删除会话"
              >
                ×
              </button>
            </div>
          ))}
        </div>
      </div>

      {/* 主聊天区域 */}
      <div 
        className={`${styles['ai-page']} ${isDragOver ? styles['drag-over'] : ''}`}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
      >
        {isDragOver && (
          <div className={styles['drag-overlay']}>
            <div className={styles['drag-message']}>
              <span className={styles['drag-icon']}>📁</span>
              <p>拖拽文件到此处上传</p>
              <small>支持图片和文档格式</small>
            </div>
          </div>
        )}
        <div className={styles['chat-header']}>
          <div className={styles['header-left']}>
            <div 
              className={styles['back-btn']} 
              onClick={() => window.history.back()}
              role="button"
              tabIndex={0}
              aria-label="返回上一页"
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  window.history.back();
                }
              }}
            >
              <span className={styles['back-icon']}>{'<'}</span>
            </div>
            <button 
              className={styles['mobile-sidebar-toggle']}
              onClick={() => setSidebarVisible(!sidebarVisible)}
              title="切换侧边栏"
            >
              <span>☰</span>
            </button>
          </div>
          <span className={styles['header-title']}>智慧AI</span>
          <div className={styles['header-shortcuts']} title="快捷键提示">
            <span className={styles['shortcut-hint']}>Ctrl+/ 聚焦输入</span>
            {isStreaming && (
              <span className={styles['shortcut-hint']} style={{ marginLeft: '8px' }}>Esc 中断回复</span>
            )}
          </div>
        </div>

      <div className={styles['chat-content']} ref={chatContentRef} style={{ flex: 1, overflowY: 'auto' }}>
        {chatMessages.map((msg, index) => {
          try {
            return (
              <div key={index} className={`${styles['message-row']} ${msg.type === 'user' ? styles['user-row'] : styles['ai-row']}`} style={{ position: 'relative' }}>
                <div className={`${styles.bubble} ${msg.type === 'user' ? styles['user-bubble'] : styles['ai-bubble']}`}>
                  {typeof msg.content === 'string' ? (
                    <span style={{ whiteSpace: 'pre-wrap', lineHeight: '1.6' }}>{msg.content}</span>
                  ) : (
                    <span></span>
                  )}
                  {msg.type === 'ai' && msg.isLoading && (
                    <div className={styles['typing-indicator']}>
                      <span></span>
                      <span></span>
                      <span></span>
                    </div>
                  )}
                  {msg.type === 'ai' && msg.showActions && (
                    <div className={styles['ai-actions']}>
                      <span className={styles['ai-action-btn']} onClick={() => handleCopy(msg, index)}>
                        {copiedIndex === index ? '已复制' : '📋'}
                      </span>
                      <span className={styles['ai-action-btn']} onClick={() => handlePlay(msg)}>
                        🔊
                      </span>
                    </div>
                  )}
                </div>
              </div>
            );
          } catch (error) {
            console.error('渲染消息时出错:', error, msg);
            return (
              <div key={index} className={`${styles['message-row']} ${styles['ai-row']}`}>
                <div className={`${styles.bubble} ${styles['ai-bubble']}`}>
                  <span style={{ color: 'red' }}>消息渲染错误</span>
                </div>
              </div>
            );
          }
        })}
      </div>

      {/* 已上传文件区域 */}
      {uploadedFiles.length > 0 && (
        <div className={styles['uploaded-files']}>
          <div className={styles['files-header']}>
            <span>已上传文件 ({uploadedFiles.length})</span>
            <button className={styles['clear-files-btn']} onClick={() => setUploadedFiles([])}>
              清空
            </button>
          </div>
          <div className={styles['files-list']}>
            {uploadedFiles.map((file) => (
              <div key={file.id} className={styles['file-item']}>
                {file.isImage ? (
                  <img 
                    src={file.preview} 
                    alt={file.name} 
                    className={styles['file-preview']}
                    onClick={() => {
                      window.open(file.preview, '_blank');
                    }}
                    style={{ cursor: 'pointer' }}
                    title="点击查看大图"
                    onError={(e) => {
                      e.target.style.display = 'none';
                      e.target.nextSibling.style.display = 'block';
                    }}
                  />
                ) : (
                  <div 
                    className={`${styles['file-preview']} ${styles['document-preview']}`}
                    style={{ 
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: '28px',
                      cursor: 'pointer',
                      width: '50px',
                      height: '50px',
                      backgroundColor: '#f5f5f5',
                      borderRadius: '8px',
                      border: '1px solid #ddd'
                    }}
                    title={`文档: ${file.name}`}
                  >
                    {typeof file.preview === 'string' ? file.preview : '📄'}
                  </div>
                )}
                <div className={styles['file-info']}>
                  <span className={styles['file-name']}>{file.name}</span>
                  <span className={styles['file-size']}>{(file.size / 1024 / 1024).toFixed(2)} MB</span>
                </div>
                <button 
                  className={styles['remove-file-btn']} 
                  onClick={() => removeFile(file.id)}
                  title="移除文件"
                >
                  ×
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className={styles['chat-input-bar']}>

        
        <div 
          className={styles['upload-btn']} 
          onClick={triggerFileUpload}
          role="button"
          tabIndex={0}
          aria-label="上传文件"
          title="选择文件上传（支持图片和文档，快捷键：Ctrl+U）"
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault();
              triggerFileUpload();
            }
          }}
        >
          <img src="/image/图片.png" alt="上传文件" style={{width: '32px', height: '32px'}} />
        </div>
        
        <input
          className={styles['chat-input']}
          placeholder="输入问题...（按Enter发送，Shift+Enter换行）"
          value={inputValue}
          onChange={e => setInputValue(e.target.value)}
          onKeyPress={handleKeyPress}
          onPaste={handlePaste}
          autoFocus
          aria-label="聊天输入框"
          title="快捷键：Ctrl+/ 聚焦，Escape 清空，Ctrl+U 上传文件"
        />

        <div className={styles['action-buttons']}>
          {isStreaming ? (
            <button 
              className={styles['stop-btn']} 
              onClick={stopAIResponse}
              aria-label="中断AI回复"
              title="中断AI回复"
            >
              <span>⏹️ 停止</span>
            </button>
          ) : (
            <button 
              className={styles['send-btn']} 
              onClick={sendMessage} 
              disabled={!inputValue.trim()}
              aria-label="发送消息"
              title="发送消息（Enter键）"
            >
              <span>发送</span>
            </button>
          )}
        </div>
      </div>

      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        multiple
        accept="image/png,image/jpeg,image/jpg,image/webp,image/gif,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        onChange={handleFileSelect}
        style={{ display: 'none' }}
      />
    </div>
    </div>
  );
}